<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App\Model\AdminUserModel;
use App\Model\AdminRolesModel;
use App\Model\AdminRoleUserModel;
use App\Model\AdminLogsModel;
use Validator;

//管理员
class AdminController extends Controller
{
    // 管理员列表
    public function index(Request $request,AdminUserModel $auModel)
    {
        //搜索条件
        $keywords = $request->input('keywords');//关键字
        $month = $request->input('month');//时间

        $pageParam['keywords'] = $keywords;
        $pageParam['month'] = $month;

        // $list = $auModel
        $list = AdminUserModel::with('roles')
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('user', 'like', "%{$keywords}%");
            })
            ->when($month, function ($query) use ($month) {
                $month_arr = explode("~",$month);
                $mintime = $month_arr[0];
                $maxtime = $month_arr[1]." 23:59:59";
                return $query->whereBetween('created_at', [$mintime,$maxtime]);
            })
			->where('type',1)
            ->orderBy('id', 'desc')
            ->paginate(10);

        //分页
        $page = $list->appends($pageParam)->links();
        return view('admin.admin.index')
            ->with('keywords',$keywords)
            ->with('month',$month)
            ->with('session_id',session('admin_id'))
            ->with('page',$page)
            ->with('list',$list);
    }

    //启用禁用
    public function up_state(Request $request,AdminUserModel $auModel)
    {
        $id = $request->post('id');//用户id
        if($id == 1){
            return returnJson(0,'禁止操作超级管理员账号');
        }
        $state = $request->post('state');//状态

        // return returnJson(0,'操作频繁'); 
        $returnArr = $auModel->updateState($id,$state);
        return response()->json($returnArr);
    }

    //添加页
    public function add(Request $request,AdminRolesModel $arModel)
    {
        //所有角色
        $roleList = $arModel->select('id','name')->get();

        return view('admin.admin.add')
            ->with('roleList',$roleList);
    }

    //添加操作
    public function insert(Request $request,AdminUserModel $auModel,AdminRoleUserModel $aruModel)
    {
        $post = $request->post();
        $validator = Validator::make($post,[
          'user'=>'required|unique:admin_users',
		  'password'=>'required',
		  'check_pass'=>'required',
        ],[
          'user.required' => '账号不能为空',
          'user.unique' => '该账号已存在',
		  'password.required' => '密码不能为空',
		  'check_pass.required' => '操作密码不能为空',
        ]);
        if($validator->fails()){
          return returnJson(0, $validator->errors()->first());
        }

        //事物
        DB::beginTransaction();
        try {
            $newid = $auModel->insertGetId(['user'=>$post['user'],'password'=>passEncryp($post['password']),'check_pass'=>passEncryp($post['check_pass'])]);
            
            if($request->filled('role')){
                $role = $request->post('role');
                foreach ($role as $v) {
                    $aruModel->insert(['role_id'=>$v,'user_id'=>$newid]);
                }
            }

            //添加日志
            $msg = "添加管理员【".$post['user']."】(id:".$newid.")";
            AdminLogsModel::addLog($msg);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return returnJson(0,'操作失败,请稍后再试');
        }
        return returnJson(1,'操作成功');
    }

    //编辑页
    public function edit(Request $request,AdminUserModel $auModel,AdminRolesModel $arModel)
    {
        //所有角色
        $roleList = $arModel->select('id','name')->get();
        // dd($roleList);
        //管理员信息
        $id = $request->post('id');//id
        $res = AdminUserModel::with('roles')
            ->where('id',$id)
            ->first();

        //拥有角色
        $roles = [];
        foreach ($res->roles as $v) {
            array_push($roles,$v['id']);
        }

        return view('admin.admin.edit')
            ->with('res',$res)
            ->with('roles',$roles)
            ->with('roleList',$roleList);
    }

    //编辑操作
    public function update(Request $request,AdminUserModel $auModel,AdminRoleUserModel $aruModel)
    {
        if(!$request->filled('id')){
            return returnJson(0, '参数错误');
        }
        $id = $request->post('id');
        $user = $request->post('user');

        //事物
        DB::beginTransaction();
        try {
            //重置密码
            if($request->filled('password')){
                $password = $request->post('password');
                
                $auModel->where('id',$id)->update(['password'=>passEncryp($password)]);
            }
			//重置操作密码
			if($request->filled('check_pass')){
				$check_pass = $request->post('check_pass');

				$auModel->where('id',$id)->update(['check_pass'=>passEncryp($check_pass)]);
			}
            //更改角色
            $aruModel->where('user_id',$id)->delete();

            if($request->filled('role')){
                $role = $request->post('role');
                foreach ($role as $v) {
                    $aruModel->insert(['role_id'=>$v,'user_id'=>$id]);
                }
            }
            //添加日志
            $msg = "编辑管理员【".$user."】(id:".$id.")信息";
            AdminLogsModel::addLog($msg);

            DB::commit();
        } catch (Exception $e) {
            DB::rollBack();
            throw $e;
            return returnJson(0,'操作失败,请稍后再试');
        }

        return returnJson(1,'操作成功'); 
    }

    //个人资料页
    public function personal(Request $request,AdminUserModel $auModel)
    {
        $id = $request->post('id');//用户id
        $res = AdminUserModel::with('roles')
            ->where('id',$id)
            ->first();

        return view('admin.admin.personal')
            ->with('res',$res);
    }

    //个人资料修改操作
    public function personalUp(Request $request,AdminUserModel $auModel)
    {
        $post = $request->post();
        $validator = Validator::make($post,[
          'id'=>'required',
          'password'=>'required',
        ],[
          'id.required' => '账号不能为空',
          'password.required' => '密码不能为空',
        ]);
        if($validator->fails()){
          return returnJson(0, $validator->errors()->first());
        }

        $auModel->where('id',$post['id'])->update(['password'=>passEncryp($post['password'])]);

        //添加日志
        $msg = "编辑管理员【".$post['user']."】(id:".$post['id'].")个人资料";
        AdminLogsModel::addLog($msg);
        //重新登陆
        session()->flush();
        return returnJson(1,'操作成功');
        // return redirect('admin/login');
    }

    //删除操作
    public function del(Request $request,AdminUserModel $auModel)
    {
        $id = $request->post('id');//用户id
        $returnArr = $auModel->delId($id);
        return response()->json($returnArr);
    }

    //管理员日志
    public function logList(Request $request,AdminLogsModel $alModel)
    {
        //搜索条件
        $keywords = $request->input('keywords');//关键字
        $month = $request->input('month');//时间

        $pageParam['keywords'] = $keywords;
        $pageParam['month'] = $month;

        $list = $alModel
            ->from('admin_logs as l')
            ->join('admin_users as a','a.id','=','l.admin_id')
            ->when($keywords, function ($query) use ($keywords) {
                return $query->where('a.user', 'like', "%{$keywords}%");
            })
            ->when($month, function ($query) use ($month) {
                $month_arr = explode("~",$month);
                $mintime = $month_arr[0];
                $maxtime = $month_arr[1]." 23:59:59";
                return $query->whereBetween('l.created_at', [$mintime,$maxtime]);
            })
            ->select('l.*','a.user as admin_user')
            ->orderBy('created_at', 'desc')
            ->paginate(10);
        // dd($list);
        //分页
        $page = $list->appends($pageParam)->links();
        return view('admin.admin.log')
            ->with('keywords',$keywords)
            ->with('month',$month)
            ->with('session_id',session('admin_id'))
            ->with('page',$page)
            ->with('list',$list);
    }
}
